package cn.xabad.server.thea.controller

import cn.xabad.server.thea.bean.TheaConfig
import cn.xabad.server.thea.ext.*
import cn.xabad.server.thea.http.AppLogService
import cn.xabad.server.thea.jpa.TheaConfigRepo
import feign.Feign
import feign.codec.StringDecoder
import feign.gson.GsonDecoder
import feign.gson.GsonEncoder
import org.joda.time.DateTime
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpEntity
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.quartz.CronScheduleBuilder
import org.quartz.CronTrigger
import org.quartz.JobDetail
import org.quartz.Scheduler
import javax.annotation.Resource


@Controller
class DemoController {


    val logger: Logger = LoggerFactory.getLogger(IndexController::class.java)
    @Value("\${buglyCookie}")
    lateinit var buglyCookie: String

    @Value("\${buglyXtoken}")
    lateinit var buglyXtoken: String

    @Autowired
    lateinit var configRepo: TheaConfigRepo

    @Value("\${accessToken}")
    lateinit var accessToken: String

    @ResponseBody
    @GetMapping("/demo/table/course")
    fun getCourse(searchId: String = "", dayDate: String): HttpEntity<*>? {
        val microCourseService = Feign.builder().encoder(GsonEncoder()).decoder(GsonDecoder())
                .requestInterceptor {
                    println("https://online-api.boxfish.cn" + it.url() + it.queryLine())
                }
                .target(AppLogService::class.java, "https://online-api.boxfish.cn")
        println(DateTime(dayDate).todayStart())
        println(DateTime(dayDate).todayEnd())
        val microCourseResult = microCourseService.queryMicroCourseInfoByGroupId(
                searchId,
                startTime = DateTime(dayDate).todayStart(),
                endTime = DateTime(dayDate).todayEnd()
        )
        if (microCourseResult.data.info.isEmpty()) {
            return null
        }
        val info = microCourseResult.data.info.first()
        info.desc = info.statePair.joinToString(separator = "<br/>") { "${DateTime(it.createTime).normal()} （${it.state}）${it.stateDesc}" }
        return ResponseEntity.ok(info)
    }

    @ResponseBody
    @GetMapping("/demo/table/user")
    fun index(userId: String = "", page: Int, limit: Int,
              startTime: Long, endTime: Long): HttpEntity<*>? {
        if (userId.isEmpty()) return null
        val appLogService = Feign.builder().encoder(GsonEncoder()).decoder(GsonDecoder())
                .requestInterceptor {
                    println("http://120.27.244.103:9302" + it.url() + it.queryLine())
                }
                .target(AppLogService::class.java, "http://120.27.244.103:9302")

        val day: String = DateTime(endTime).toString("yyyyMMdd")
        val log = appLogService.queryLog(
                userId, day, startTime = startTime, endTime = endTime,
                page = page - 1, size = limit,
                dataAccessToken = accessToken)
        for (item in log.data.content.filterNot { it.key == "student_stop_speech_evaluation_infoR" }) {
            if (DateTime(item.time).onlyDay() != DateTime(item.msgReceiveTime).onlyDay()) {
                item.timeError = true
            }
            if (Math.abs(DateTime(item.time).millis - DateTime(item.msgReceiveTime).millis) > (1000 * 60)) {
                item.timeError = true
            }
            if (item.properties.debug_message.isNullOrEmpty()) {
                item.properties.debug_message = ""
            }
            val content = StringBuilder()
            when (item.type) {
                "profile_set" -> {
                }
                "track" -> {
                    when (item.key) {
                        "boxfish_debug" -> {
                            var msg = item.properties.debug_message ?: ""
                            when {
                                msg.startsWith("打开摄像头->") -> msg = if (md5(userId) == msg.substringAfter("打开摄像头->")) {
                                    "自己，打开了摄像头"
                                } else {
                                    "对方，打开了摄像头"
                                }
                                msg.startsWith("开摄像头，user：") -> msg = if (md5(userId) == msg.substringAfter("开摄像头，user：").substringBefore(",")) {
                                    "自己打开摄像头"
                                } else {
                                    "对方打开摄像头"
                                }
                                msg.startsWith("收到第一帧：") -> msg = if (md5(userId) == msg.substringAfter("收到第一帧：").substringBefore("开始计时").trim()) {
                                    "收到自己首帧"
                                } else {
                                    "收到对方首帧"
                                }
                                msg.startsWith("有成员开摄像头，type：1；user：") -> msg = if (md5(userId) == msg.substringAfter("有成员开摄像头，type：1；user：").trim()) {
                                    "自己，打开了摄像头"
                                } else {
                                    "对方，打开了摄像头"
                                }
                            }
                            content.append(msg)
                        }
                        "boxfish_kill" -> {
                            content.append("手动杀掉了APP")
                        }
                        "online_course_heartbeat" -> {
                            content.append("心跳")
                        }
                        "student_button_click" -> {
                            content.append(item.properties.button)
                        }
                        "student_critical_path" -> {
                            content.append("${item.properties.critical_path_prepage} 跳转到 -> ${item.properties.critical_path_page}")
                        }
                        else -> {
                            content.append(item.key)
                        }
                    }
                }
                "end_session" -> {
                    content.append("<span style=\"color:blue;\">退到后台</span>")
                }
                "begin_session" -> {
                    content.append("<span style=\"color:blue;\">回到前台</span>")
                }
                else -> {
                    content.append(item.type)
                }
            }
            item.properties.debug_message = content.toString()
        }
        return ResponseEntity.ok(log.data)
    }

    @ResponseBody
    @GetMapping("/demo/table/crash")
    fun getCrash(userId: String = "", dayDate: String): HttpEntity<*>? {
        val values = configRepo.findByK("buglyCookie")
        if (values.isEmpty())
            return ResponseEntity.ok(mapOf("" to "-1", "msg" to "buglyCookie null"))

        val crashService = Feign.builder().decoder(StringDecoder())
                .requestInterceptor {
                    it.header("Cookie", buglyCookie)
                    it.header("X-token", buglyXtoken)
                    println("https://bugly.qq.com" + it.url() + it.queryLine())
                }
                .target(AppLogService::class.java, "https://bugly.qq.com")
        val result = crashService.queryCrash(dayDate, dayDate, userId)
        return ResponseEntity.ok(result)
    }

    @ResponseBody
    @GetMapping("/demo/save")
    fun saveMobile(key: Long, v: String): HttpEntity<*>? {
        val values = configRepo.findByV(v)
        if (values.isEmpty()) {
            val config = TheaConfig(id = 0, k = key.toString(), v = v)
            configRepo.save(config)
        } else {
            configRepo.updateByV(key.toString(), v)
        }
        return ResponseEntity.EMPTY
    }

    @ResponseBody
    @GetMapping("/checkDevice")
    fun getMobile(deviceId: String): HttpEntity<*>? {
        return ResponseEntity.ok(configRepo.findByV(deviceId))
    }

    @ResponseBody
    @GetMapping("/demo/list")
    fun getMobile(): HttpEntity<*>? {
        val values = configRepo.findAll().sortedBy { it.k }
        return ResponseEntity.ok(values.map { it.v to it.k }.toMap())
    }

    @ResponseBody
    @GetMapping("/demo/resetToken")
    fun resetToken(): HttpEntity<*>? {
        val microCourseService = Feign.builder().encoder(GsonEncoder()).decoder(GsonDecoder())
                .requestInterceptor {
                    println("http://test.xabad.cn" + it.url() + it.queryLine())
                }
                .target(AppLogService::class.java, "http://test.xabad.cn")
        val token  = microCourseService.requestToken()
        this.accessToken = token.data
        return ResponseEntity.ok(token)
    }

    @ResponseBody
    @GetMapping("/demo/json")
    fun toJson(): HttpEntity<*>? {
        val map = mapOf("userId" to "1298907", "date" to "2018-06-08")
        return ResponseEntity.ok(listOf(map))
    }
}